package com.bjc.service.impl;

import com.bjc.dao.OrderDao;
import com.bjc.dao.TxLogDao;
import com.bjc.domain.Order;
import com.bjc.domain.TxLog;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * @program: spring-cloud-alibaba
 * @description: 发送半事务消息
 * @author: bjc
 * @create: 2021-08-08 21:19
 */
@Service
public class OrderTransaction {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private TxLogDao txLogDao;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void createOrderBefore(Order order){
        //当作全局事务id
        String txId = UUID.randomUUID().toString();

        //发送半事务消息
        rocketMQTemplate.sendMessageInTransaction("tx_producer_group",
                "tx_topic",
                MessageBuilder.withPayload(order).setHeader("txId",txId).build(),
                order);
    }

    @Transactional
    public void createOrder(String txId, Order order) {
        orderDao.save(order);
        TxLog txLog = new TxLog();
        txLog.setTxId(txId);
        txLog.setDate(new Date());
        txLogDao.save(txLog);
    }
}
